package com.freedo.demo.domain.imp;

import java.math.BigInteger;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

import com.freedo.demo.domain.i.IBaseDao;

/**
 * 执行
 * @author murong
 *
 */
@Repository(value="baseDao")
public class BaseDao implements IBaseDao {

	
	@PersistenceContext
	private EntityManager entityManager;
	
	@Override
	public int exec(String sql, Object[] params) {
		// TODO Auto-generated method stub
		Query query = entityManager.createNativeQuery(sql);
		for (int i = 0; i < params.length; i++) {
			query.setParameter(i+1, params[i]);
		}
		int result = query.executeUpdate();
		return result;
	}
	@Override
	public int exec_count(String sql, Object[] params) {
		// TODO Auto-generated method stub
		Query query = entityManager.createNativeQuery(sql);
		for (int i = 0; i < params.length; i++) {
			query.setParameter(i+1, params[i]);
		}
		return ((BigInteger) query.getSingleResult()).intValue();

	}
	@Override
	public Object exec_single(String sql, Object[] params) {
		// TODO Auto-generated method stub
		Query query = entityManager.createNativeQuery(sql);
		for (int i = 0; i < params.length; i++) {
			query.setParameter(i+1, params[i]);
		}
		List<Object> ents = (List<Object>)(List)query.getResultList();
		if(ents.size()>0)
		{
			return ents.get(0);
		}
		return null;
	}
	@Override
	public List<Object> exec_list(String sql, Object[] params) {
		// TODO Auto-generated method stub
		Query query = entityManager.createNativeQuery(sql);
		for (int i = 0; i < params.length; i++) {
			query.setParameter(i+1, params[i]);
		}
		return query.getResultList();
	}

}
